#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_QuitOnClose, false);
    setAttribute(Qt::WA_DeleteOnClose, false);
    settingsDialog = 0;

    ui->browser->page()->settings()->setAttribute(QWebSettings::JavascriptEnabled,true);
    ui->browser->page()->settings()->setAttribute(QWebSettings::PluginsEnabled,true);
    ui->browser->page()->settings()->setAttribute(QWebSettings::JavaEnabled,false);
    ui->browser->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    ui->browser->page()->networkAccessManager()->setCookieJar(new CookieJar(this));
    ui->browser->load(APP_DESKTOP_URL);

    quitAction = new QAction(u("В&ыход"), this);
    connect(quitAction, SIGNAL(triggered()), this, SLOT(quit()));

    aboutAction = new QAction(u("&О программе..."), this);
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));

    openSettingsDialogAction = new QAction(u("Н&астройки..."), this);
    connect(openSettingsDialogAction, SIGNAL(triggered()), this, SLOT(openSettingsDialog()));

    showHideAction = new QAction(u("Показать &главное окно"), this);
    showHideAction->setCheckable(true);
    showHideAction->setChecked(true);
    connect(showHideAction, SIGNAL(triggered()), this, SLOT(showHide()));

    playPauseAction = new QAction(u("Пауза/продолж&ить"), this);
    playPauseAction->setEnabled(false);
    connect(playPauseAction, SIGNAL(triggered()), this, SLOT(playPause()));

    stopAction = new QAction(u("&Стоп"), this);
    stopAction->setEnabled(false);
    connect(stopAction, SIGNAL(triggered()), this, SLOT(stop()));

    nextAction = new QAction(u("Проп&устить"), this);
    nextAction->setEnabled(false);
    connect(nextAction, SIGNAL(triggered()), this, SLOT(next()));

    trayIconMenu = new QMenu(this);

    trayIconMenu->addAction(showHideAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(playPauseAction);
    trayIconMenu->addAction(nextAction);
    trayIconMenu->addAction(stopAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(openSettingsDialogAction);
    trayIconMenu->addAction(aboutAction);
    trayIconMenu->addAction(quitAction);

    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);
    QIcon icon;
    icon.addFile(":/icon");
    icon.addFile(":/icon16");
    trayIcon->setIcon(QIcon(":/icon16"));
#ifdef Q_WS_MAC
    trayIcon->setIcon(QIcon(":/icon16-mac"));
#endif
#ifndef Q_OS_MACX
    qApp->setWindowIcon(icon);
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(showHide(QSystemTrayIcon::ActivationReason)));
    setWindowIcon(icon);
#endif
    trayIcon->setToolTip(windowTitle());
    trayIcon->show();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::quit()
{
    qApp->exit(0);
}

void MainWindow::about()
{
    QString txt;
    txt += u("<font size=\"6\">Твоё Радио Десктоп</font><br/>");
    txt += u("версия ")+qApp->applicationVersion();
    txt += u("<br/><br/>");
    txt += "<a href=\""+APP_URL+u("\">Веб-версия</a><br/>");
    txt += "<a href=\""+CLUB_URL+u("\">Группа &laquo;В Контакте&raquo;</a>");
    //txt += "<a href=\""+HELP_URL+u("\">Помощь</a>"); // Не работает :(
    QMessageBox::about(this, u("О программе"), txt);
}


void MainWindow::playPause()
{
    ui->browser->page()->mainFrame()->evaluateJavaScript("play_pause()");
}

void MainWindow::next()
{
    ui->browser->page()->mainFrame()->evaluateJavaScript("play_next()");
}

void MainWindow::stop()
{
    ui->browser->page()->mainFrame()->evaluateJavaScript("stop()");
}

void MainWindow::showHide()
{
    setVisible(!isVisible());
    if (isVisible()) {
        setWindowState(Qt::WindowActive);
    }
}

void MainWindow::showHide(QSystemTrayIcon::ActivationReason reason)
{
    if (QSystemTrayIcon::Trigger==reason)
        showHide();
}

void MainWindow::openSettingsDialog()
{
    if (!settingsDialog) {
        settingsDialog = new SettingsDialog(this);
    }

    settingsDialog->show();
    /*settingsDialog->raise();
    settingsDialog->activateWindow();*/
}


void MainWindow::on_browser_linkClicked(QUrl url)
{
    QDesktopServices::openUrl(url);
}

void MainWindow::hideEvent(QHideEvent *event)
{
    showHideAction->setChecked(false);
    event->accept();
}

void MainWindow::showEvent(QShowEvent *event)
{
    showHideAction->setChecked(true);
    event->accept();
}

void MainWindow::on_browser_urlChanged(QUrl url)
{
    QString track_title, track_artist;
    QString hash = url.encodedFragment();
    // Исправление бага вконтакте
    if (url.toString().startsWith("http://vkontakte.ru/api/login_success.html")) {
        url.setEncodedHost("tvoeradio.org");
        url.setEncodedPath("/php/desktop-success.php");
        url.setEncodedQuery(QByteArray("v=").append(qApp->applicationVersion()));
        ui->browser->load(url);
    }
    // Да-да, вот такой кривой способ отлова сообщений от приложения
    if (hash.startsWith("playing_")) {
        track_artist = ui->browser->page()->mainFrame()->evaluateJavaScript("current_track.artist").value<QString>();
        track_title = ui->browser->page()->mainFrame()->evaluateJavaScript("current_track.title").value<QString>();
        setWindowTitle(track_artist+u(" — ")+track_title+u(" — Твоё Радио"));
        QSettings settings;
        if (settings.value("Interface/Notifications", true).toBool()) {
            QFileInfo *t = new QFileInfo("/usr/bin/notify-send");
            if (t->exists()) {
                QString cmd = "notify-send -i tvoeradio-desktop \""+track_title.replace("\"", "\\\"")+"\" \""+track_artist.replace("\"", "\\\"")+"\"";
                system(cmd.toUtf8());
            } else {
                trayIcon->showMessage(track_title, track_artist, QSystemTrayIcon::NoIcon, 2000);
            }
            delete t;

        }
        playPauseAction->setEnabled(true);
        stopAction->setEnabled(true);
        nextAction->setEnabled(true);
    } else {
        playPauseAction->setEnabled(false);
        stopAction->setEnabled(false);
        nextAction->setEnabled(false);
        setWindowTitle(u("Твоё Радио"));
        if (hash.startsWith("logout_")) {
            ((CookieJar*)ui->browser->page()->networkAccessManager()->cookieJar())->clear();
            ui->browser->load(APP_DESKTOP_URL);
        }
    }
    trayIcon->setToolTip(windowTitle());
}
